<template>
  <a-modal
    class="select-commodity"
    :visible="formVisible"
    okText="确定"
    cancelText="取消"
    :title="title"
    :maskClosable="false"
    :destroyOnClose="true"
    :keyboard="false"
    :closable="false"
    :confirmLoading="confirmLoading"
    width="1000px"
    @cancel="closeModal()"
    @ok="handleSubmit">
    <a-tabs :activeKey="activeKey" @change="tabsChange">
      <a-tab-pane :key="'1'" tab="商品">
        <search-table
          :url="goodsListUrl"
          ref="searchtable"
          :columns="goodsColumns"
          :defaultParams="defaultParams"
          :headParams="headParams"
          :tableSelectType="'radio'"
          :form="form"
          :beforeRenderFunc="beforeRenderFunc"
          @selectedRowChange="handleSelectRowSelect">
          <!-- 搜索条件 -->
          <template slot="searchForm">
            <a-form layout="inline" :form="form">
              <a-form-item label="商品名称">
                <a-input
                  style="width:180px"
                  v-decorator="[
                    'goodsName',
                  ]"
                  placeholder="请输入商品名称">
                </a-input>
              </a-form-item>
              <a-form-item label="商品分类">
                <a-tree-select
                  allowClear
                  style="width:180px"
                  :replaceFields="{children:'children', title:'classifyName', key:'id', value: 'id' }"
                  v-decorator="[
                    'goodsClassificationId',
                  ]"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="productClassifyList"
                  placeholder="请选择"
                  tree-default-expand-all
                  >
                  <span slot="title" slot-scope="{ value }">
                      {{ value }}
                  </span>
                </a-tree-select>
              </a-form-item>
              <a-form-item label="商品类目">
                  <a-tree-select
                    allowClear
                    style="width:180px"
                    :replaceFields="{children:'children', title:'categoryName', key:'id', value: 'id' }"
                    v-decorator="[
                      'goodsCategoryId',
                    ]"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    :tree-data="productCategoryList"
                    placeholder="请选择"
                    tree-default-expand-all
                    >
                    <span slot="title" slot-scope="{ value }">
                        {{ value }}
                    </span>
                </a-tree-select>
              </a-form-item>
              <a-form-item label="商品分组">
                <a-tree-select
                    allowClear
                    style="width:180px"
                    :replaceFields="{children:'children', title:'groupName', key:'id', value: 'id' }"
                    v-decorator="[
                      'goodsGroupId',
                    ]"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    :tree-data="productGroupList"
                    placeholder="请选择"
                    tree-default-expand-all
                    >
                    <span slot="title" slot-scope="{ value }">
                        {{ value }}
                    </span>
                </a-tree-select>
              </a-form-item>
              <a-form-item v-show="userInfo.shopRoleCode == 'role:store:main'" label="商品所属">
                <a-select style="width: 180px"
                  v-decorator="[
                    'goodsAscription',
                  ]" :allowClear="true" placeholder="全部" :options="goodsAscriptionList"></a-select>
              </a-form-item>
                </a-form>
          </template>
        </search-table>
      </a-tab-pane>
      <!-- <a-tab-pane key="2" tab="Tab 2">
        Content of Tab Pane 2
      </a-tab-pane> -->
    </a-tabs>
    <template slot="footer">
      <a-button :loading="confirmLoading" key="submit" type="primary" @click="handleSubmit"> 添加 </a-button>
      <a-button key="back" @click="closeModal"> 关闭 </a-button>
    </template>
  </a-modal>
</template>

<script>
  import { createOptionsByDict } from '@/utils/dict'
  export default {
    name: "selectCommodity",
    props: {
      hasChosenGoodsIds: { // 已被选择的商品id集合
        type: Array,
        default:() => []
      },
    },
    data() {
      return {
        formVisible: false, // 是否显示选择商品弹窗
        activeKey: '1', // 当前活动的tab
        title: '选择商品', // 弹窗标题
        goodsListUrl: '/goods/page', // 列表接口地址
        form: this.$form.createForm(this, { name: "table_search" }), // 搜索条件表格
        headParams: {  }, // 列表接口域名
        defaultParams: {
          goodsStatus: 2,
          marketingType:3
        }, // 列表默认携带参数
        confirmLoading: false, // 弹窗提交状态
        productClassifyList:[], // 商品分类
        productCategoryList:[], // 商品类目
        productGroupList:[], // 商品分组
        goodsAscriptionList:[ // 商品所属
          {
            label:'本店商品',
            value:1
          },{
            label:'总店商品',
            value:2
          }
        ],
        goodsStatusList:[ // 商品状态
          {
            label:'仓库中',
            value:1
          },{
            label:'上架',
            value:2
          },{
            label:'已下架',
            value:3
          },
        ],
        goodsColumns: [
          {
            title: "商品名称",
            dataIndex: "goodsName",
            width: 300,
            key: "goodsName",
            customRender: (text, row) => {
              return <div class="product_td"><table-img src={row.goodsPicture}/><div class="product_name">{text}</div></div>
            }
          },
          {
            title: "价格",
            dataIndex: "salePrice",
            key: "salePrice",
            customRender:(text,row)=>{
              return ((text||0)/100).toFixed(2);
            }
          },
          {
            title: "总可售库存",
            dataIndex: "goodsInventoryTotal",
            key: "goodsInventoryTotal",
            customRender: (text, record) => {
              return text ? (text + (record.goodsUnitCode ? findDictNameByValue('GOOD_INVENTORY_UNIT', record.goodsUnitCode) : '')) : ''
            }
          },
          {
            title: "销量",
            dataIndex: "realSales",
            key: "realSales",
          },
          {
            title: "状态",
            dataIndex: "goodsStatus",
            key: "goodsStatus",
            customRender:(text,row)=>{            
              return (this.getStatusLabelByStatusValue(text) || {}).label;
            }
          },
          {
            title: "商品分类",
            dataIndex: "goodsClassificationName",
            key: "goodsClassificationName",
          },
          {
            title: "创建时间",
            dataIndex: "createDate",
            key: "createDate",
          },
        ],
        goodsInfo: {} // 商品信息
      }
    },
    computed:{
      userInfo(){
        return this.$store.getters.userInfo || {};
      }
    },
    created(){
      this.getProductClassify(); // 分类
      this.getProductGroup(); // 分组
      this.getProductCategory(); // 类目
    },
    methods: {
      // tab切换
      tabsChange(val) {
        this.activeKey = val
      },
      // 处理表格数据
      beforeRenderFunc(data) {
        let _this = this
        data.dataInfo.records.forEach(item => {
          if(_this.hasChosenGoodsIds.includes(item.id)) {
            item.disabled = true
          }
        })
        return data
      },
      // 商品状态
      getStatusLabelByStatusValue(value){
        return this.goodsStatusList.find(item=>{
          return item.value==value;
        })
      },
      // 商品分类
      async getProductClassify(){
        let res=await this.$get('/goods/classify/tree',{
          shopId:this.userInfo.shopId || ''
        });
        if(res && res.returnCode=='1000'){
          this.productClassifyList=res.dataInfo || [];
        }
        else {
          this.productClassifyList=[];
        }
      },
      // 商品类目
      async getProductCategory(){
        let res=await this.$get('/goods/category/tree',{
          categoryStatus:1
        },false,true);
        if(res && res.returnCode=='1000'){
          this.productCategoryList=res.dataInfo || [];
        }
        else {
          this.productCategoryList=[];
        }
      },
      // 商品分组
      async getProductGroup(){
        let res=await this.$get('/goods/group/tree',{
          shopId:this.userInfo.shopId || ''
        },false,true);
        if(res && res.returnCode=='1000'){
          this.productGroupList=res.dataInfo || [];
        }
        else {
          this.productGroupList=[];
        }
      },
      // 选择商品
      handleSelectRowSelect(record) {
        console.log(record)
        if(record[0]){
          this.goodsInfo = record[0]
        }
      },
      // 确定提交
      handleSubmit() {
        this.confirmLoading = true;
        if(this.goodsInfo.id) {
          this.confirmLoading = false;
          this.goodsInfo.commodityType = this.activeKey
          this.$emit('chooseGoods', this.goodsInfo);
        } else {
          this.$confirm({
            title: '关闭确认',
            content: '还未选择商品，确认要关闭选择窗口吗？',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
              this.closeModal()
            }
          });
        }
      },
      // 取消
      closeModal() {
        this.formVisible = false;
        this.confirmLoading = false;
      },
    }
  }
</script>

<style lang="less" scoped>
  .product_td{
    display: flex;
    align-items: center;
    .product_name{
      margin-left:6px;
    }
  }
</style>
